package Synchronized;

//synchronized 作用于实例方法

public class AccountingSync implements Runnable{
    //共享资源  （临界资源）
    static  int i=0;

    //对当前实例对象加锁
    synchronized void increase(){
        i++;
    }
    @Override
    public void run() {
        for(int i=0;i<1000000;i++){
            increase();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //获得2个不同实例的锁---线程不安全
        AccountingSync accountingSync1=new AccountingSync();
        AccountingSync accountingSync2=new AccountingSync();
        Thread thread1=new Thread(accountingSync1);
        Thread thread2=new Thread(accountingSync2);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("i="+i);
        //输出 i=1104786


    }
    public static void main1(String[] args) throws InterruptedException {
        //获得同一个实例的同一把锁 ----线程安全
        AccountingSync accountingSync=new AccountingSync();
        Thread thread1=new Thread(accountingSync);
        Thread thread2=new Thread(accountingSync);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("i="+i);
        //输出结果 i=2000000
    }
}
